<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2018/11/9
 * Time: 13:25
 */

namespace Activity\Controller;

use Activity\Model\ActivityModel;
use Common\Controller\HomebaseController;
use Order\Model\OrderModel;
use Wx\Controller\WxPayController;
require_once "./simplewind/Lib/Util/Curl.class.php";

class ActivityController extends HomebaseController{

    protected $act_model;
    protected $order_model;
    protected $page_size;

    function _initialize() {
        parent::_initialize();
        $this->page_size    = 10;
        $this->act_model    = M('activity');
        $this->order_model  = D("Order/Order");
    }

    // 活动列表
    public function activity_list()
    {
        $where  = 'a.status = 1 ';
        $search = I('search');
        if ($search) {
            $this->assign('search', $search);
            $where .= ' and a.name like "%' . $search . '%" ';

            // 标签相关
            $label_ids  = M('label')->where(['name' => ['like', "%$search%"]])->limit(0)->select();
            $label_ids  = _array_column($label_ids, 'id');
            if (!empty($label_ids)) {
                $where .= 'or ( ';
                foreach ($label_ids as $k => $v) {
                    if ($k == count($label_ids) - 1) {
                        $where .= " FIND_IN_SET( $v, a.labels) ";
                    } else {
                        $where .= " FIND_IN_SET( $v, a.labels) or ";
                    }
                }
                $where .= ')';
            }
        }

        $count  = $this->act_model->alias('a')->where($where)->count();
        $page   = $this->page($count, $this->page_size);
        $lists  = $this->act_model
            ->alias('a')
            ->join('__AREA__ a1 on a.city_id = a1.id', 'left')
            ->where($where)
            ->limit($page->firstRow , $page->listRows)
            ->order("sort desc, start_time desc")
            ->field('a.*, a1.areaname as city_name, (SELECT GROUP_CONCAT(name) FROM rx_label WHERE FIND_IN_SET(id, a.labels)) as label_names')
            ->select();

        $act_model = new ActivityModel();
        foreach ($lists as $k => $v) {
            if (strtotime($v['end_time']) > time() || empty($v['link_addr'])) {
                $v['link_addr']     = U('Activity/Activity/activity_info', ['id' => $v['id']]);
            }
            $act_status             = get_activity_status($v);
            $v['act_status']        = $act_status['des'];
            $v['act_status_code']   = $act_status['status'];
            $v['label_names']       = array_slice(explode(',', $v['label_names']), 0, 1);
            $v['form_type_name']    = $act_model->activity_form_array[$v['act_form']];
            $v['start_time']        = date("Y.m.d H:i", strtotime($v['start_time']));
            $v['end_time']          = date("Y.m.d H:i", strtotime($v['end_time']));
            $v['thumb']             = json_decode($v['thumb'], true);
            $lists[$k] = $v;
        }
        $this->assign("page", $page->show('default'));
        $this->assign("lists", $lists);
        $this->assign('total_pages', ceil($count / $this->page_size));
        $this->display();
    }

    // 活动详情页
    public function activity_info()
    {
        $id = I('get.id');
        if ($id) {
            $activity_info = M('activity')
                ->alias('a')
                ->join('__AREA__ a1 on a.city_id = a1.id', 'left')
                ->join('__ACTIVITY_GROUP__ ag on a.activity_group_id = ag.id', 'left')
                ->where(['a.id' => $id, 'a.status' => 1])
                ->field('a.*, a1.areaname as city_name, ag.group_name')
                ->find();

            if ($activity_info) {

                $now = time();
                if (strtotime($activity_info['buy_ticket_time']) < $now && strtotime($activity_info['start_time']) > $now) {
                    $activity_info['can_buy_ticket'] = 1;
                } else {
                    $activity_info['can_buy_ticket'] = 0;
                }

                $thumb = json_decode($activity_info['thumb'], true);
                if (sp_is_mobile()) {
                    $activity_info['img'] = $thumb['mb_page_thumb'];
                } else {
                    $activity_info['img'] = $thumb['pc_page_thumb'];
                }

                // 活动已结束，并且有跳转链接的情况下
                if (strtotime($activity_info['end_time']) < time() && !empty($activity_info['link_addr'])) {
                    $this->redirect($activity_info['link_addr']);
                } else {
                    $ticket_lists   = M('act_ticket')->where(['act_id' => $id])->order('sort desc')->limit(0)->select();
                    $guest_lists    = M('activity_guest')->where(['act_id' => $id, 'show' => 1])->order('sort desc')->limit(0)->select();
                    $step_lists     = M('activity_step')->where(['act_id' => $id])->order('sort desc')->limit(0)->select();
                    $bright_lists   = M('activity_bright')->where(['act_id' => $id])->limit(0)->select();
                    $host_h_lists   = M('activity_host')->where(['act_id' => $id, 'host_type' => 1])->order('sort desc')->limit(0)->select();
                    $host_c_lists   = M('activity_host')->where(['act_id' => $id, 'host_type' => 2])->order('sort desc')->limit(0)->select();
                    foreach ($step_lists as $k => $v) {
                        $step_guest = M('activity_guest')->where(['act_id' => $id, 'id' => ['IN', $v['step_guests']]])->select();
                        $step_lists[$k]['step_guest_info'] = $step_guest;
                    }
                    $this->assign('ticket_lists', $ticket_lists);
                    $this->assign('guest_lists', $guest_lists);
                    $this->assign('step_lists', $step_lists);
                    $this->assign('bright_lists', $bright_lists);
                    $this->assign('host_h_lists', $host_h_lists);
                    $this->assign('host_c_lists', $host_c_lists);
                    $this->assign('activity_info', $activity_info);

                    //同组活动
                    if ($activity_info['activity_group_id']) {
                        $exit_citys = M('activity')
                            ->alias('a')
                            ->join('__AREA__ a1 on a.city_id = a1.id', 'left')
                            ->where(['a.activity_group_id' => $activity_info['activity_group_id'], 'a.status' => 1])
                            ->field('a.id, a1.areaname as city_name')
                            ->select();
                        $exit_citys = array_column($exit_citys, 'city_name', 'id');

                        // 分组信息
                        $group_info     = M('activity_group')->where(['id' => $activity_info['activity_group_id']])->find();
                        $city_names     = array_filter(explode(',', $group_info['city_names']));
                        $group_citys    = array();
                        foreach ($city_names as $k => $city_name) {
                            $act_id = array_search($city_name, $exit_citys);
                            if ($act_id) {
                                $group_citys[] = ['city_name' => $city_name, 'act_id' => $act_id];
                            } else {
                                $group_citys[] = ['city_name' => $city_name, 'act_id' => 0];
                            }
                        }
                        $this->assign('group_citys', $group_citys);
                    }

                    // 用户是否登录并且有oa_openid
                    $get_base_info = false;
                    $user = sp_get_current_user();
                    if ($user && !$user['oa_openid']) {
                        $get_base_info = true;
                    }
                    $this->assign('get_base_info', $get_base_info);
                    $show_mobile_input = false;
                    if ($user && !$user['mobile']) {
                        $show_mobile_input = true;
                    }
                    $this->assign('show_mobile_input', $show_mobile_input);

                    // 跳转锚点
                    $has_click_buy = session('has_click_buy');
                    if ($has_click_buy) {
                        $this->assign('has_click_buy', 1);
                        session('has_click_buy', null);
                    }

                    // 进入相应的页面模板
                    $this->display('activity_info_' . $activity_info['page_type']);
                }
            } else {
                $this->error('这个活动溜走了。');
            }
        } else {
            $this->error('这个活动溜走了。。');
        }
    }

    // 活动报名,买票
    public function activity_buy_ticket()
    {
        $user_info      = sp_get_current_user();
        $act_id         = I('act_id');
        $redirect_url   = U('Activity/Activity/activity_info', ['id' => $act_id]);
        if (!$user_info) {
            session('has_click_buy', 1);
            $this->error('请先登录', U('User/Login/index', ['redirect' => base64_encode($redirect_url)]));exit;
        }

        // 绑定手机操作
        $mobile = I('get.mobile', 0, 'intval');
        if (!$user_info['mobile']) {
            if ($mobile) {
                $update = ['mobile' => $mobile];
                if (!$user_info['user_pass']) {
                    $update['user_pass'] = sp_password('123456');
                }
                M('users')->where(['id' => $user_info['id']])->save($update);
                $user_info = M('users')->where(['id' => $user_info['id']])->find();
                sp_update_current_user($user_info);
            } else {
                session('has_click_buy', 1);
                $this->error('请先绑定手机，以便工作人员联系您');exit;
            }
        }

        $user_id        = $user_info['id'];
        $order_id       = I('get.order_id', '0', 'intval');
        $buy_info       = I('get.buy_info');
        $pay_type       = I('get.pay_type', '0', 'intval');     // 支付方式

        if ($order_id) {
            // 继续支付，直接使用之前的订单号进行支付
            $order_info = $this->order_model->where(['id' => $order_id])->find();
            if ($order_info) {
                if ($order_info['created_at'] + OrderModel::ORDER_EXPIRE_TIME > time()) {
                    $attach             = $pay_type;
                    $trade_order_id     = $this->order_model->pay_exisit_order($order_id);
                    $total_fee          = $order_info['total_money'];
                    $ticket_id          = $order_info['goods_id'];
                    if ($pay_type == OrderModel::ORDER_PAY_TYPE_WX_NATIVE) {
                        // 微信支付--native 扫码支付
                        $wx = new WxPayController();
                        $wx->send_native_pay_request("活动购票", $attach, $trade_order_id, $total_fee, $ticket_id);

                    } elseif ($pay_type == OrderModel::ORDER_PAY_TYPE_WX_H5) {
                        // 微信支付--H5 扫码支付
                        $wx             = new WxPayController();
                        $redirect_url   = 'http://' . C('DOMAIN_NAME') . $redirect_url;
                        $pay_url        = $wx->send_h5_pay_request("活动购票", $attach, $trade_order_id, $total_fee, $redirect_url);
                        $data           = array('status' => 1, 'pay_url' => $pay_url);
                        $this->ajaxReturn($data);

                    } elseif ($pay_type == OrderModel::ORDER_PAY_TYPE_WX_JSAPI) {
                        // 微信支付--JASPI 公众号内调起微信支付
                        $wx     = new WxPayController();
                        $user   = sp_get_current_user();
                        if (empty($user['oa_openid'])) {
                            session('user', null);
                            $this->error('请用微信重新登录', U('User/Login/index', ['redirect' => base64_encode($redirect_url)]));
                        } else {
                            $parameters = $wx->getJsapiPayParameters("活动购票", $attach, $trade_order_id, $total_fee, $ticket_id, $user['oa_openid']);
                            $this->assign('parameters', $parameters);
                            $this->display();exit;
                        }
                    } else {
                        $this->error('请选择正确的支付方式');
                    }
                } else {
                    $this->error('订单已过期，请重新下单');
                }
            } else {
                $this->error('订单信息有误，请重新下单');
            }
        } else {
            $buy_info = explode(',', $buy_info);
            foreach ($buy_info as $v) {
                list($ticket_id, $ticket_num) = explode('|', $v);
                $temp_buy_info[$ticket_id] = $ticket_num;
            }
            $re = $this->pre_deal_buy_info($temp_buy_info, $user_id);
            if ($re['status'] == 1) {
                $total_fee      = $re['total_fee'];
                $trade_order_id = $re['trade_order_id'];
                $attach         = $pay_type;

                if ($pay_type == OrderModel::ORDER_PAY_TYPE_WX_NATIVE) {
                    // 微信支付--native 扫码支付
                    $wx = new WxPayController();
                    $wx->send_native_pay_request("活动购票", $attach, $trade_order_id, $total_fee, $trade_order_id);

                } elseif ($pay_type == OrderModel::ORDER_PAY_TYPE_WX_H5) {
                    // 微信支付--H5 扫码支付
                    $wx             = new WxPayController();
                    $redirect_url   = 'http://' . C('DOMAIN_NAME') . $redirect_url;
                    $pay_url        = $wx->send_h5_pay_request("活动购票", $attach, $trade_order_id, $total_fee, $redirect_url);
                    $data           = array('status' => 1, 'pay_url' => $pay_url);
                    $this->ajaxReturn($data);

                } elseif ($pay_type == OrderModel::ORDER_PAY_TYPE_WX_JSAPI) {
                    // 微信支付--JASPI 公众号内调起微信支付
                    $wx     = new WxPayController();
                    $user   = sp_get_current_user();
                    if (empty($user['oa_openid'])) {
                        session('user', null);
                        $this->error('请用微信重新登录', U('User/Login/index', ['redirect' => base64_encode($redirect_url)]));
                    } else {
                        $parameters = $wx->getJsapiPayParameters("活动购票", $attach, $trade_order_id, $total_fee, $trade_order_id, $user['oa_openid']);
                        $this->assign('parameters', $parameters);
                        $this->display();exit;
                    }
                } else {
                    $this->error('请选择正确的支付方式');
                }
            } else {
                $this->error($re['msg']);
            }
        }
    }

    // 活动兑换实体票的二维码
    public function get_exchange_qrcode()
    {
        $this->check_login();
        $order_id = I('order_id');
        if ($order_id) {
            $order_info = M('order')->where(['id' => $order_id, 'status' => OrderModel::ORDER_STATUS_HAS_PAY, 'exchange' => 0])->find();
            if ($order_info) {
                $ticket_info = M('act_ticket')->where(['id' => $order_info['goods_id']])->find();
                if ($ticket_info) {
                    $where    = ['id' => $ticket_info['act_id'], 'end_time' => ['EGT', date('Y-m-d H:i:s')], 'status' => 1];
                    $act_info = M('activity')->where($where)->find();
                    if ($act_info) {
                        // 二维码
                        $url = 'http://' . C('DOMAIN_NAME') . U('Activity/Activity/exchange_paper_ticket', ['order_id' => $order_id]);
                        require_once './plugins/WxPay/lib/phpqrcode.php';
                        \QRcode::png($url,false, '0', 3);
                    }
                }
            }
        }
    }


    // 检票 -- 兑换纸质票
    public function exchange_paper_ticket()
    {
        $order_id = I('order_id');
        if ($order_id) {
            $this->assign('order_id', $order_id);
            $order_info = M('order')->where(['id' => $order_id, 'status' => OrderModel::ORDER_STATUS_HAS_PAY])->find();
            if ($order_info) {

                if ($order_info['exchange'] != 0) {
                    $this->error('该票已兑换');
                    exit;
                }

                $ticket_info = M('act_ticket')->where(['id' => $order_info['goods_id']])->find();
                if ($ticket_info) {
                    $where      = ['id' => $ticket_info['act_id'], 'end_time' => ['EGT', date('Y-m-d H:i:s')], 'status' => 1];
                    $act_info   = M('activity')->where($where)->find();
                    if ($act_info) {

                        $ticket_code = I('ticket_code');
                        if ($ticket_code) {
                            // 兑换
                            if ($ticket_code == $act_info['ticket_code']) {
                                M('order')->where(['id' => $order_id])->save(['exchange' => 1]);
                                $this->success('~兑换成功~');
                            } else {
                                $this->error('兑换码不正确');
                            }
                        } else {
                            // 展示信息
                            $user_info  = M('users')->where(['id' => $order_info['user_id']])->find();
                            $info       = array(
                                'ticket_name'   => $ticket_info['name'],
                                'create_time'   => $order_info['created_at'],
                                'mobile'        => substr_replace($user_info['mobile'],'****',3,4),
                                'price'         => $ticket_info['price'],
                                'ticket_num'    => $order_info['goods_num'],
                                'act_name'      => $act_info['name'],
                                'user_name'     => $user_info['user_nicename'],
                            );
                            $this->assign('status', '兑换ING');
                            $this->assign('order_id', $order_id);
                            $this->assign('info', $info);
                            $this->display();
                        }
                    } else {
                        $this->error('出票信息有误，请联系客服');
                    }
                } else {
                    $this->error('出票信息有误，请联系客服');
                }
            } else {
                $this->error('出票信息有误，请联系客服');
            }
        } else {
            $this->error('出票信息有误，请联系客服');
        }
    }

    // 异步检查
    private function curl_reborn_ticket($act_id)
    {
        $curl = new \Curl();
        $curl->get('http://' . C('DOMAIN_NAME') . '/index.php?g=Activity&m=Activity&a=check_reborn_ticket&id=' . $act_id, '', '', '', '', 0);
    }


    // 检查未支付的票，增加库存
    public function check_reborn_ticket() {
        $act_id = I('get.id', '0', 'intval');
        if (!empty($act_id)) {
            $act_info = M('activity')->where(['id' => $act_id, 'status' => 1])->find();
            if ($act_info && (strtotime($act_info['start_time']) > time())) {

                $ticket_model   = M('act_ticket');
                $order_model    = M('order');
                $tickets        = $ticket_model->where(['act_id' => $act_id])->field("id")->select();
                $tickets        = implode(',', _array_column($tickets, 'id'));

                if ($tickets) {
                    $where = array();
                    $where['type']          = OrderModel::ORDER_TYPE_ACT_TICKET;    // 订单类型 1-活动
                    $where['status']        = OrderModel::ORDER_STATUS_NOT_PAY;     // 订单未付款
                    $where['goods_id']      = array('in', $tickets);
                    $where['created_at']    = array('ELT', time() - OrderModel::ORDER_EXPIRE_TIME);
                    $expire_orders          = $order_model->where($where)->select();

                    foreach ($expire_orders as $order) {
                        $goods_id   = $order['goods_id'];
                        $goods_num  = $order['goods_num'];

                        // 设置订单失效
                        $order_model->where(['id' => $order['id']])->save(['status' => OrderModel::ORDER_STATUS_EXPIRE]);

                        // 增加票的库存
                        $ticket_model->where(['id' => $goods_id])->save(array('remain_num' => array('exp', "remain_num + " . $goods_num)));
                    }
                }
            }
        }
    }

    // 预处理购票请求
    public function pre_deal_buy_info($buy_info, $user_id)
    {
        if (empty($buy_info) || empty($user_id)) {
            return ['status' => -1, 'msg' => '参数错误'];
        }

        $return             = array('status' => 1);
        $now                = time();
        $new_orders         = array();
        $trade_order_id     = 0;
        $total_fee          = 0;

        foreach ($buy_info as $ticket_id => $ticket_num) {
            $ticket_info = M('act_ticket')->where(['id' => $ticket_id])->find();
            if ($ticket_info) {
                $act_info = M('activity')->where(['id' => $ticket_info['act_id'], 'status' => 1])->find();
                if (!empty($act_info)) {
                    if (strtotime($act_info['end_time']) < $now) {
                        // 活动已结束
                        $return['status']   = -2;
                        $return['msg']      = '活动已结束';
                        break;

                    } elseif (strtotime($act_info['start_time']) < $now) {
                        // 活动已开始
                        $return['status']   = -3;
                        $return['msg']      = '活动已开始';
                        break;

                    } else {
                        $canBuy = $this->order_model->checkTicketLimit($user_id, OrderModel::ORDER_TYPE_ACT_TICKET, $ticket_id, $ticket_info['pre_limit']);
                        if ($canBuy == 0) {
                            $return['status']   = -4;
                            $return['msg']      = "您的【 " . $ticket_info['name'] . " 】购票数已达上限";
                            break;

                        } elseif ($ticket_num > $canBuy) {
                            $return['status']   = -5;
                            $return['msg']      = '您还可以购买' . $canBuy . "张【 " . $ticket_info['name'] . " 】";
                            break;

                        } else {
                            // 检查是否有重复订单
                            $notBuy = $this->order_model->CheckOldOrder($user_id, OrderModel::ORDER_TYPE_ACT_TICKET, $ticket_id, $ticket_num * $ticket_info['price'] * 100,  $trade_order_id);
                            if (array_key_exists('trade_order_id', $notBuy)) {
                                // 可以沿用之前的订单
                                $trade_order_id = $notBuy['trade_order_id'];
                            } else {
                                // 生成新的订单
                                if ($ticket_info['remain_num'] <= 0) {
                                    // 票售罄
                                    $this->curl_reborn_ticket($act_info['id']);
                                    $return['status']   = -6;
                                    $return['msg']      = '【 ' . $ticket_info['name'] . ' 】都被带走了，待会刷新试试吧';
                                    break;

                                } elseif ($ticket_num > $ticket_info['remain_num']) {
                                    //  票不足
                                    $return['status']   = -7;
                                    $return['msg']      = '【 ' . $ticket_info['name'] . ' 】剩余票数不足';
                                    break;

                                } else {
                                    // 修改库存
                                    $ticket_re = M('act_ticket')->where(['id' => $ticket_id])->save(array('remain_num' => array('exp', "remain_num - " . $ticket_num)));
                                    if ($ticket_re) {
                                        $re = $this->order_model->CreateOrder($user_id, OrderModel::ORDER_TYPE_ACT_TICKET, $ticket_id, $ticket_num, $ticket_num * $ticket_info['price'] * 100, $trade_order_id);
                                        if ($re['status'] == 1) {
                                            $new_orders[]   = $re['order_id'];
                                            $trade_order_id = $re['trade_order_id'];
                                        } else {
                                            // 订单生成失败，库存增加
                                            M('act_ticket')->where(['id' => $ticket_id])->save(array('remain_num' => array('exp', "remain_num + " . $ticket_num)));

                                            $return['status']   = -8;
                                            $return['msg']      = $re['msg'];
                                            break;
                                        }
                                    } else {
                                        //  票不足
                                        $this->curl_reborn_ticket($act_info['id']);

                                        $return['status']   = -9;
                                        $return['msg']      = '剩余【 ' . $ticket_info['name'] . ' 】不足，待会刷新试试吧';
                                        break;
                                    }
                                }
                            }

                            $total_fee += $ticket_num * $ticket_info['price'] * 100;
                        }
                    }
                } else {

                    $return['status']   = -10;
                    $return['msg']      = '活动参数错误';
                    break;
                }
            } else {
                $return['status']   = -11;
                $return['msg']      = "活动参数错误";
                break;
            }
        }

        if ($return['status'] == 1) {
            $return['total_fee']        = $total_fee;
            $return['trade_order_id']   = $trade_order_id;
        } else {
            // 产生新订单的票都退回去
            if (!empty($new_orders)) {
                $order_model = M('order');
                foreach ($new_orders as $order_id) {
                    $order_info = $order_model->where(['id' => $order_id])->find();
                    if ($order_info) {
                        M('act_ticket')->where(['id' => $order_info['goods_id']])->save(array('remain_num' => array('exp', "remain_num + " . $order_info['goods_num'])));
                        $order_model->where(['id' => $order_id])->save(['status' => OrderModel::ORDER_STATUS_EXPIRE]);
                    }
                }
            }
        }
        return $return;
    }
}

